package com.example.myfirst.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.myfirst.dao.UserDao;
import com.example.myfirst.dto.UserDto;
import com.example.myfirst.entity.User;
import com.example.myfirst.service.UserService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @ApiModelProperty("查询所有用户信息")
    @Override
    public List<User> queryAllUser() {
        List<User> userList = userDao.selectList(null);
        return userList;
    }

    @ApiModelProperty("添加用户")
    @Override
    public boolean addUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        int i = userDao.insert(user);
        return i > 0;
    }

    @ApiModelProperty("根据用户id删除")
    @Override
    public boolean delUserByID(Integer id) {
        int i = userDao.deleteById(id);
        return i > 0;
    }

    @ApiModelProperty("根据id查询用户信息")
    @Override
    public List<User> queryUserById(Integer id) {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("id", id);
        return userDao.selectList(qw);
    }

    @ApiModelProperty("根据id修改用户信息")
    @Override
    public Boolean updateUserById(User user, Integer id) {
        user.setUpdateTime(LocalDateTime.now());
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("id", id);
        int i = userDao.update(user, qw);
        return i > 0;
    }

    @ApiModelProperty("用户登录")
    @Override
    public UserDto login(String username, String password) {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("username", username);
        qw.eq("password", password);
        User user = userDao.selectOne(qw);
        if (user != null) {
            return new UserDto(user.getId(), user.getUsername(), user.getAddress(), UUID.randomUUID().toString());
        } else {
            return null;
        }
    }

}
